//
//  AppDelegate.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2018/12/18.
//  Copyright © 2018 wpkj. All rights reserved.
//

#import "AppDelegate.h"
#import "FEGuideViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

#pragma mark - 判断当前应用是否需要显示新特性界面
- (BOOL)isNewVersion {
    NSString * key = @"CFBundleShortVersionString";
    // 取出沙盒中存储的上次使用软件的版本号
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *lastVersion = [defaults stringForKey:key];
    // 获得当前软件的版本号
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
    if ([currentVersion isEqualToString:lastVersion]) {// 不是新版本
        return NO;
    } else { // 新版本
        // 存储新版本
        [defaults setObject:currentVersion forKey:key];
        [defaults synchronize];
        return YES;
    }
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
#pragma mark - 监听网络状态
    [NetworkUtils reachabilityStatusChange];
    //创建tabbarController
//    if ([self isNewVersion]) {
//        self.window.rootViewController = [[FEGuideViewController alloc] init];
//    } else {
        HEBaseTabBarController *tabbarVC = [[HEBaseTabBarController alloc] init];
        self.window.rootViewController = tabbarVC;
//    }
    //设置window显示
    [self.window makeKeyAndVisible];
    
    NSArray *extensionArray = [NSArray arrayWithObjects:@"doc", @"docx", @"ppt", @"pptx", @"xls", @"xlsx",@"mp3",@"mp4",@"rft",@"rtf",@"pages",@"key",@"numbers",nil];

    for (int i=0; i<[extensionArray count]; i++) {
        NSString *fileExtension = [extensionArray objectAtIndex:i];
        NSString *utiString = (__bridge NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,(__bridge CFStringRef)fileExtension,NULL);
        NSLog(@"Extension: %@ UTI:%@",fileExtension,utiString);
    }
    
#pragma mark - 关于键盘的设置
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    keyboardManager.enable = YES; // 控制整个功能是否启用
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    keyboardManager.shouldToolbarUsesTextFieldTintColor = NO; // 控制键盘上的工具条文字颜色是否用户自定义
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarByPosition; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
    keyboardManager.enableAutoToolbar = YES; // 控制是否显示键盘上的工具条
    keyboardManager.shouldShowToolbarPlaceholder = YES; // 是否显示占位文字
    keyboardManager.placeholderFont = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12]; // 设置占位文字的字体
    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离
    
    #if __IPHONE_OS_VERSION_MAX_ALLOWED >=130000
        if (@available(iOS 13.0, *)) {
            self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
        }else{
            
        }
    #else
        //xcode baseSDK为7.0以下的
    #endif
    
#pragma mark - 调试时打开
#ifdef DEBUG
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
#else
    
#endif
    return YES;
}


void uncaughtExceptionHandler(NSException *exception) {
    NSLog(@"CRASH: %@", exception);
    NSLog(@"Stack Trace: %@", [exception callStackSymbols]);
    // Internal error reporting
}


- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths lastObject];
    if (url != nil) {
        NSString *path = [url absoluteString];
        path = [path stringByRemovingPercentEncoding];
        NSMutableString *string = [[NSMutableString alloc] initWithString:path];
        if ([path hasPrefix:@"file:///private"]) {
            [string replaceOccurrencesOfString:@"file:///private" withString:@"" options:NSCaseInsensitiveSearch  range:NSMakeRange(0, path.length)];
        }
        NSArray *tempArray = [string componentsSeparatedByString:@"/"];
        NSString *fileName = tempArray.lastObject;
        NSString *sourceName = options[@"UIApplicationOpenURLOptionsSourceApplicationKey"];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",sourceName,fileName]];
        if ([fileManager fileExistsAtPath:filePath]) {
            NSLog(@"文件已存在");
            //文件已经存在,直接打开
            [MBProgressHUD showTipMessageInWindow:@"文件已存在"];
        } else {
            //文件不存在,会自动保存
//            [self downloadDocxWithURL:[ValidateUtils validateNull:dict[@"path"]] docPath:documentsDirectory fileName:docPath tag:tag forLabel:underlineLabel];
            [MBProgressHUD showTipMessageInWindow:@"文件已保存到下载"];
        }
    }
    return true;
}


- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation {
    NSLog(@"openURL method was called");
    NSLog(@"the source application is: %@", sourceApplication);
    NSLog(@"url is: %@", url);
    NSLog(@"handle the file in above file path for the shared doc");
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
